package com.charon.auth.demo.controller;

import com.charon.auth.common.entity.ImageCode;
import com.charon.auth.common.handler.ImageCodeHandler;
import com.charon.auth.enumeration.ValidateCodeSesiionKey;
import com.charon.auth.properties.ImageCodeProperties;
import com.charon.auth.properties.SMSCodeProperties;
import com.charon.auth.properties.SecurityProperties;
import com.charon.common.util.ImageCodeUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
  *@ClassName: ValidateCodeController
  *@Description: 图形验证码
  *@Author: Charon [248135724@qq.com]
  *@Date: 2019/1/29 0029 11:07
  *@Version: 1.0
  */
@RestController
public class ValidateCodeController {


    /**
     * 该对象依赖Social包
     */
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    /**
     * security配置，包括基本配置（手机或浏览器配置），图形验证码配置等。
     */
    @Autowired
    private SecurityProperties securityProperties;

    @GetMapping("/code/image")
    public void imageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        ImageCodeProperties imageCodeProperties = securityProperties.getCode().getImage();
        ImageCode imageCode= ImageCodeHandler.createImageCode(request,imageCodeProperties);
        // sessionStrategy会去request中获取session，将第二个参数作为session的attribute的key，
        // 注意：第二个参数一定要和验证码过滤器中的参数相同。
        sessionStrategy.setAttribute(new ServletWebRequest(request),
                ValidateCodeSesiionKey.SESSION_KEY.getTitle(),imageCode);
        ImageIO.write(imageCode.getImage(),"JPEG",response.getOutputStream());

    }

    @GetMapping("/code/sms")
    public void smsCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        SMSCodeProperties smsCodeProperties = securityProperties.getCode().getSms();

        // sessionStrategy会去request中获取session，将第二个参数作为session的attribute的key，
        // 注意：第二个参数一定要和验证码过滤器中的参数相同。
        sessionStrategy.setAttribute(new ServletWebRequest(request),
                ValidateCodeSesiionKey.SESSION_KEY.getTitle(),xxxx);

    }

}
